package com.amigo.online.provider.adv.aspect;

import java.lang.reflect.Field;

import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Order(-98) // 多个Aspect 顺序越小越先执行！
@Component
public class HeaderAopAction {

    private static final Logger logger = LoggerFactory.getLogger(HeaderAopAction.class);

    /**
     * @Title: pointCutMethod @Description: (定义Controller拦截规则) @param: @return:
     * void @throws
     */
    @Pointcut("@annotation(com.amigo.online.provider.adv.aspect.RequestHeaderEntity)")
    private void pointCutMethod() {
    }

    /**
     * 映射requesteHeader
     *
     * @param joinPoint
     * @param requestHeaderEntity
     */
    @Before(value = "pointCutMethod() && @annotation(requestHeaderEntity)") // 使用上面定义的切入点
    public void Log(JoinPoint joinPoint, RequestHeaderEntity requestHeaderEntity) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        Object[] args = joinPoint.getArgs();
        for (Object obj : args) {
            if (obj.getClass().getSimpleName().equals(requestHeaderEntity.target())) {
                try {
                    Class<?> objClass = obj.getClass();
                    for (Field field : objClass.getDeclaredFields()) {
                        field.getModifiers();
                        field.setAccessible(true);
                        Named named = field.getAnnotation(Named.class);
                        if (named != null) {
                            if (StringUtils.isNotEmpty(named.value())) {
                                field.set(obj, request.getHeader(named.value()));
                            }
                        } else {
                            field.set(obj, request.getHeader(field.getName()));
                        }
                    }
                } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
                    logger.error(e.toString());
                }
            }
        }
        logger.info("------获取请求头成功------");
    }
}
